<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        label-width="100px"
        class="ele-form-search"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="商户名称:">
              <el-input
                clearable
                v-model="where.keyword"
                placeholder="请输入商户名称或手机号"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :where="where"
        :datasource="url"
        :columns="columns"
        :selection.sync="selection"
        height="calc(100vh - 315px)"
        cache-key="chuandaoMerchantTable">

        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit(null)">添加商户
          </el-button>
          <el-button
            size="small"
            type="success"
            icon="el-icon-download"
            class="ele-btn-icon"
            @click="exportData">导出数据
          </el-button>
        </template>

        <!-- 商户名称列 -->
        <template slot="name" slot-scope="{row}">
          <div style="display: flex; align-items: center;">
            <el-avatar
              :size="32"
              :src="row.avatar || ''"
              style="margin-right: 8px;">
              {{ row.name.charAt(0) }}
            </el-avatar>
            <div>
              <div style="font-weight: 500;">{{ row.name }}</div>
              <div style="color: #909399; font-size: 12px;">ID: {{ row.id }}</div>
            </div>
          </div>
        </template>

        <!-- 余额列 -->
        <template slot="balance" slot-scope="{row}">
          <div style="text-align: right;">
            <span style="color: #E6A23C; font-weight: 500; font-size: 16px;">
              ¥{{ parseFloat(row.balance || 0).toFixed(2) }}
            </span>
          </div>
        </template>

        <!-- 状态列 -->
        <template slot="status" slot-scope="{row}">
          <el-tag
            :type="row.status === 1 ? 'success' : 'danger'"
            size="small">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>

        <!-- 创建时间列 -->
        <template slot="create_time" slot-scope="{row}">
          {{ formatDate(row.create_time) }}
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="showMerchantDetail(row)">详情
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-money"
            @click="showRechargeDialog(row)"
            style="color: #E6A23C;">充值
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-refresh"
            @click="syncMerchantBalance(row)"
            style="color: #67C23A;">同步
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-document"
            @click="showWalletHistory(row)">流水
          </el-button>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 商户详情弹窗 -->
    <el-dialog
      title="商户详情"
      :visible.sync="detailVisible"
      width="600px"
      :close-on-click-modal="false">
      <div v-if="currentMerchant">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商户ID">{{ currentMerchant.id }}</el-descriptions-item>
          <el-descriptions-item label="商户名称">{{ currentMerchant.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentMerchant.mobile }}</el-descriptions-item>
          <el-descriptions-item label="当前余额">
            <span style="color: #E6A23C; font-weight: 500;">
              ¥{{ parseFloat(currentMerchant.balance || 0).toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentMerchant.status === 1 ? 'success' : 'danger'" size="small">
              {{ getStatusText(currentMerchant.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentMerchant.create_time) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(currentMerchant.update_time) }}</el-descriptions-item>
          <el-descriptions-item label="船到商户ID">{{ currentMerchant.origin_id || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 商户充值弹窗组件 -->
    <merchant-recharge-dialog
      :visible.sync="rechargeVisible"
      :merchant-data="currentMerchant"
      @recharge-success="handleRechargeSuccess">
    </merchant-recharge-dialog>

    <!-- 钱包流水弹窗 -->
    <el-dialog
      title="钱包流水"
      :visible.sync="walletVisible"
      width="900px"
      :close-on-click-modal="false">
      <div v-if="currentMerchant" style="margin-bottom: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
        <strong>{{ currentMerchant.name }}</strong> - {{ currentMerchant.mobile }}
        <span style="color: #E6A23C; margin-left: 20px;">当前余额: ¥{{ parseFloat(currentMerchant.balance || 0).toFixed(2) }}</span>
      </div>

      <!-- 流水筛选 -->
      <el-form :model="walletWhere" inline style="margin-bottom: 15px;">
        <el-form-item label="交易类型">
          <el-select v-model="walletWhere.transaction_type" clearable placeholder="请选择" style="width: 120px;">
            <el-option label="充值" :value="1"></el-option>
            <el-option label="消费" :value="2"></el-option>
            <el-option label="退款" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="walletDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadWalletData">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 流水列表 -->
      <el-table :data="walletData" v-loading="walletLoading" style="width: 100%;">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="交易类型" width="100">
          <template slot-scope="{row}">
            <el-tag :type="getTransactionTypeColor(row.transaction_type)" size="small">
              {{ getTransactionTypeText(row.transaction_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template slot-scope="{row}">
            <span :style="{color: row.amount > 0 ? '#67C23A' : '#F56C6C'}">
              {{ row.amount > 0 ? '+' : '' }}¥{{ parseFloat(row.amount).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="balance_after" label="余额" width="120">
          <template slot-scope="{row}">
            ¥{{ parseFloat(row.balance_after).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column prop="created_at" label="时间" width="160">
          <template slot-scope="{row}">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="walletTotal > 0"
        style="margin-top: 15px; text-align: center;"
        @size-change="handleWalletSizeChange"
        @current-change="handleWalletCurrentChange"
        :current-page="walletPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="walletLimit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="walletTotal">
      </el-pagination>

      <div slot="footer">
        <el-button @click="walletVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getMerchantWallet, syncMerchantBalance, exportMerchantData } from '@/api/chuandao';
import MerchantRechargeDialog from './components/MerchantRechargeDialog.vue';

export default {
  name: 'ChuandaoMerchantIndex',
  components: {
    MerchantRechargeDialog
  },
  data() {
    return {
      // 表格配置
      url: 'chuandao/merchant/list',
      where: {
        keyword: ''
      },
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center'
        },
        {
          prop: 'id',
          label: 'ID',
          width: 80,
          align: 'center'
        },
        {
          prop: 'name',
          label: '商户信息',
          slot: 'name',
          minWidth: 200
        },
        {
          prop: 'mobile',
          label: '手机号',
          width: 130
        },
        {
          prop: 'balance',
          label: '账户余额',
          slot: 'balance',
          width: 120,
          align: 'right'
        },
        {
          prop: 'status',
          label: '状态',
          slot: 'status',
          width: 80,
          align: 'center'
        },
        {
          prop: 'create_time',
          label: '创建时间',
          slot: 'create_time',
          width: 160
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 200,
          slot: 'action',
          align: 'center'
        }
      ],
      selection: [],

      // 弹窗状态
      detailVisible: false,
      rechargeVisible: false,
      walletVisible: false,

      // 当前商户
      currentMerchant: null,


      // 钱包流水
      walletData: [],
      walletLoading: false,
      walletTotal: 0,
      walletPage: 1,
      walletLimit: 20,
      walletWhere: {
        transaction_type: null
      },
      walletDateRange: null
    };
  },
  methods: {
    // 重新加载表格
    reload() {
      this.$refs.table.reload();
    },

    // 重置搜索
    reset() {
      this.where = {
        keyword: ''
      };
      this.reload();
    },

    // 显示商户详情
    showMerchantDetail(row) {
      this.currentMerchant = row;
      this.detailVisible = true;
    },

    // 显示充值弹窗
    showRechargeDialog(row) {
      console.log('充值按钮被点击，商户信息:', row);
      this.currentMerchant = row;
      this.rechargeVisible = true;
      console.log('弹窗状态设置为:', this.rechargeVisible);
    },

    // 充值成功处理
    handleRechargeSuccess(data) {
      // 刷新表格数据
      this.reload();

      // 更新当前商户余额（如果在详情弹窗中）
      if (this.currentMerchant && this.currentMerchant.id === data.merchant_id) {
        this.currentMerchant.balance = data.new_balance;
      }

      // 显示成功提示（组件内已处理，这里可以添加额外逻辑）
      console.log('充值成功:', data);
    },

    // 同步商户余额
    async syncMerchantBalance(row) {
      try {
        // 使用确认框提示用户
        await this.$confirm('确定要同步该商户的余额吗？', '确认同步', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        });

        // 显示加载状态
        const loading = this.$loading({
          lock: true,
          text: '正在同步余额...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        const res = await syncMerchantBalance(row.id);

        loading.close();

        if (res.code === 200) {
          const syncData = res.data;
          const { sync_type, difference, platform_balance, local_balance_before, local_balance_after } = syncData;

          // 根据同步类型显示不同的消息
          if (sync_type === 'auto_recharge') {
            this.$message.success(`余额同步成功！自动充值¥${difference}，当前余额：¥${local_balance_after}`);
            
            // 刷新表格以显示最新的余额
            this.reload();

          } else if (sync_type === 'platform_lower') {
            this.$message.warning({
              message: `注意：平台余额(¥${platform_balance})低于本地余额(¥${local_balance_before})，请检查是否有未同步的消费记录`,
              duration: 5000
            });

          } else {
            this.$message.success(`余额已同步，当前余额：¥${local_balance_after}`);
          }

          // 显示详细的同步结果通知
          this.$notify({
            title: `商户 ${row.name} 余额同步完成`,
            message: `
              <div style="line-height: 1.5;">
                <p><strong>平台余额：</strong>¥${platform_balance}</p>
                <p><strong>本地余额：</strong>¥${local_balance_before}</p>
                ${sync_type === 'auto_recharge' ? `<p><strong>自动充值：</strong>¥${difference}</p>` : ''}
                <p><strong>同步后余额：</strong>¥${local_balance_after || local_balance_before}</p>
                <p><strong>同步时间：</strong>${syncData.sync_time}</p>
              </div>
            `,
            dangerouslyUseHTMLString: true,
            type: sync_type === 'auto_recharge' ? 'success' : 'info',
            duration: 8000
          });

        } else {
          this.$message.error(res.message || '同步余额失败');
        }

      } catch (error) {
        if (error === 'cancel') {
          // 用户取消操作，不显示错误消息
          return;
        }
        
        console.error('同步余额失败:', error);
        this.$message.error('同步请求失败，请检查网络连接');
      }
    },

    // 显示钱包流水
    showWalletHistory(row) {
      this.currentMerchant = row;
      this.walletVisible = true;
      this.walletPage = 1;
      this.walletWhere = {
        transaction_type: null
      };
      this.walletDateRange = null;
      this.loadWalletData();
    },

    // 加载钱包流水数据
    loadWalletData() {
      this.walletLoading = true;
      const params = {
        page: this.walletPage,
        limit: this.walletLimit,
        transaction_type: this.walletWhere.transaction_type
      };

      // 添加日期范围
      if (this.walletDateRange && this.walletDateRange.length === 2) {
        params.start_date = this.walletDateRange[0];
        params.end_date = this.walletDateRange[1];
      }

      getMerchantWallet(this.currentMerchant.id, params).then(res => {
        if (res.code === 200) {
          this.walletData = res.data.list || [];
          this.walletTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取流水失败');
        }
      }).catch(error => {
        console.error('获取钱包流水失败:', error);
        this.$message.error('获取流水失败，请重试');
      }).finally(() => {
        this.walletLoading = false;
      });
    },

    // 钱包流水分页
    handleWalletSizeChange(val) {
      this.walletLimit = val;
      this.walletPage = 1;
      this.loadWalletData();
    },

    handleWalletCurrentChange(val) {
      this.walletPage = val;
      this.loadWalletData();
    },


    // 导出数据
    async exportData() {
      try {
        // 显示加载提示
        const loading = this.$loading({
          lock: true,
          text: '正在导出数据，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 构建导出参数 - 根据是否有选中记录决定导出模式
        let params;
        if (this.selection && this.selection.length > 0) {
          // 选中导出模式：传递选中的ID数组，忽略搜索条件
          params = {
            mode: 'selected',
            ids: this.selection.map(item => item.id)
          };
          console.log('选中导出模式，导出记录ID:', params.ids);
        } else {
          // 条件导出模式：传递搜索条件
          params = {
            mode: 'filter',
            keyword: this.where.keyword
          };
          console.log('条件导出模式，搜索关键词:', params.keyword);
        }

        // 调用导出API
        const response = await exportMerchantData(params);
        
        loading.close();

        // 创建下载链接
        const blob = new Blob([response], { type: 'text/csv;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        
        // 生成文件名 - 根据导出模式添加标识
        const now = new Date();
        const timestamp = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0') + 
          String(now.getSeconds()).padStart(2, '0');
        
        const modeText = params.mode === 'selected' ? '选中记录' : '筛选结果';
        link.download = `船到商户数据_${modeText}_${timestamp}.csv`;
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        // 显示成功提示
        const exportCount = params.mode === 'selected' ? params.ids.length : '符合条件的';
        this.$message.success(`数据导出成功！已导出${exportCount}条记录`);

      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败：' + (error.message || '网络错误'));
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '正常',
        0: '禁用',
        2: '审核中'
      };
      return statusMap[status] || '未知';
    },

    // 获取交易类型文本
    getTransactionTypeText(type) {
      const typeMap = {
        1: '充值',
        2: '消费',
        3: '退款'
      };
      return typeMap[type] || '未知';
    },

    // 获取交易类型颜色
    getTransactionTypeColor(type) {
      const colorMap = {
        1: 'success',  // 充值
        2: 'warning',  // 消费
        3: 'info'      // 退款
      };
      return colorMap[type] || '';
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
.ele-form-search {
  margin-bottom: 15px;
}

.ele-form-actions {
  text-align: left;
}

/* 表格内操作按钮样式 */
.el-button--text {
  padding: 0;
  margin-right: 10px;
}

.el-button--text:last-child {
  margin-right: 0;
}

/* 商户信息展示样式 */
.merchant-info {
  display: flex;
  align-items: center;
}

.merchant-info .avatar {
  margin-right: 10px;
}

.merchant-info .name {
  font-weight: 500;
}

.merchant-info .id {
  color: #909399;
  font-size: 12px;
}

/* 余额显示样式 */
.balance {
  color: #E6A23C;
  font-weight: 500;
  font-size: 16px;
}

/* 钱包流水金额样式 */
.amount-positive {
  color: #67C23A;
}

.amount-negative {
  color: #F56C6C;
}

/* 弹窗内表格样式调整 */
.el-dialog__body .el-table {
  margin-bottom: 0;
}

/* 分页样式调整 */
.el-pagination {
  text-align: center;
  margin-top: 15px;
}

/* 商户信息卡片样式 */
.merchant-card {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}
</style>
